﻿using System.Collections.Generic;

namespace Auktionshuset___Server
{
    public class AuctionMonitor
    {
        private static readonly Dictionary<int, Auction> Auctions = new Dictionary<int, Auction>();
        private static readonly object SyncRoot = new object();

        public Auction Get(int auctionId)
        {
            lock (SyncRoot)
            {
                return Auctions[auctionId];
            }
        }

        public void Add(Auction auction)
        {
            lock (SyncRoot)
            {
                Auctions.Add(auction.Id, auction);
            }
        }

        public void Remove(Auction auction)
        {
            Remove(auction.Id);
        }

        public void Remove(int auctionId)
        {
            lock (SyncRoot)
            {
                Auctions.Remove(auctionId);
            }
        }

        public List<Auction> GetAuctions()
        {
            lock (SyncRoot)
            {
                return new List<Auction>(Auctions.Values);
            }
        }

        public void SubscribeTo(int auctionId, Client client)
        {
            Auction auction = Get(auctionId);
            lock (SyncRoot)
            {
                auction.Subscribers.Add(client);
            }
        }

        public void UnsubscribeTo(int auctionId, Client client)
        {
            Auction auction = Get(auctionId);
            lock (SyncRoot)
            {
                auction.Subscribers.Remove(client);
            }
        }

        public List<Client> GetSubscribers(Auction auction)
        {
            lock (SyncRoot)
            {
                return new List<Client>(auction.Subscribers);
            }
        } 
    }
}
